#include <cmath>
#include <iostream>
#include <sstream>
#include "IidTimestamp.h"

namespace conex {

	IidTimestamp::IidTimestamp(iid_type iid):m_Iid(iid), m_Tm(NULL)
	{

	}

	iid_type IidTimestamp::GetTimeStamp()
	{
		iid_type iid = 0;
		m_t = time(NULL);
		m_Tm = localtime(&m_t);
		if(m_Tm)
		{
			iid = m_Tm->tm_sec*10000
				+ m_Tm->tm_min* 1000000
				+ m_Tm->tm_hour*(long long)100000000
				+ m_Tm->tm_mday*(long long)10000000000
				+ (m_Tm->tm_mon+1)*(long long)1000000000000
				+ (m_Tm->tm_year+1900)*(long long)100000000000000;
		}


		if(m_Iid >= iid)
			m_Iid ++;
		else
			m_Iid = iid;

		return m_Iid;	
	}

	tm IidTimestamp::GetDatetime(const iid_type &iid)
	{
		int year = static_cast<int>(  iid/100000000000000  - 1900);
		int mon = static_cast<int>(   iid/1000000000000 % 100 - 1);
		int mday = static_cast<int>(  iid/10000000000 % 100);
		int hour = static_cast<int>(  iid/100000000 % 100);
		int min = static_cast<int>(   iid/1000000 % 100);
		int sec = static_cast<int>(   iid/10000 % 100);
		tm _tm;
		_tm.tm_year = year;
		_tm.tm_mon = mon;
		_tm.tm_mday = mday;
		_tm.tm_hour = hour;
		_tm.tm_min = min;
		_tm.tm_sec = sec;
		return _tm;
	}

	string IidTimestamp::GetIid() {
		iid_type iid = GetTimeStamp();
		stringstream ss;
		ss << iid;		
		return ss.str();
	}

	string IidTimestamp::GetCurrentTime(iid_type iid) {
		tm tm_datetime = GetDatetime(iid);
		string result = (tm_datetime.tm_year+1900) + "-";
		result.append((tm_datetime.tm_mon+1) + "-" );
		result.append(tm_datetime.tm_mday + "-" );
		result.append(tm_datetime.tm_hour + "-"); 
		result.append(tm_datetime.tm_min + "-");
		result.append(tm_datetime.tm_sec + "");
		return result;
	}

}